package com.ponhu.ea2.goodsCenter.provider.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ponhu.ea2.constants.DictConstant;
import com.ponhu.ea2.dto.PhInventoryBaseDto;
import com.ponhu.ea2.dto.PhInventoryForCloudTradeDto;
import com.ponhu.ea2.dto.PhInventoryForGoodsCenterDto;
import com.ponhu.ea2.dto.PhInventoryForPurchaseDto;
import com.ponhu.ea2.entity.*;
import com.ponhu.ea2.enums.InventoryChannelEnum;
import com.ponhu.ea2.goodsCenter.provider.config.WxMappingJackson2HttpMessageConverter;
import com.ponhu.ea2.goodsCenter.provider.mapper.*;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsDataCreateorupdateLogService;
import com.ponhu.ea2.goodsCenter.provider.service.InventoryService;
import com.ponhu.ea2.goodsCenter.provider.service.PhSysDictItemService;
import com.ponhu.ea2.goodsCenter.provider.utils.DingTalkHandler;
import com.ponhu.ea2.goodsCenter.provider.utils.JsonUtils;
import com.ponhu.ea2.properties.GoodsProperties;
import com.ponhu.ea2.service.facade.GoodsCenterForPonHuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luyu
 * @create 2021-10-22 17:02
 */
@RefreshScope
@Slf4j
@Service
public class GoodsCenterForPonHuServiceImpl implements GoodsCenterForPonHuService {

    @Resource
    MaterialMapper materialMapper;

    @Resource
    PhModelMapper phModelMapper;

    @Resource
    PhSeriesMapper phSeriesMapper;

    @Resource
    PhBrandMapper phBrandMapper;

    @Resource
    PhCategoryMappingMapper phCategoryMappingMapper;

    @Resource
    PhSysDictItemService phSysDictItemService;

    @Resource
    private GoodsDataCreateorupdateLogService goodsDataCreateorupdateLogService;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private GoodsInventoryMdMapper goodsInventoryMdMapper;

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    DingTalkHandler dingTalkHandler;

    @Value("${third-party.ponhu.createUrl}")
    private String createUrl;

    @Value("${third-party.ponhu.updateUrl}")
    private String updateUrl;

    @Resource
    GoodsProperties goodsProperties;

    /**
     * 创建商品信息
     *
     * @param inventoryDto
     * @return
     */
    @Override
    public Boolean createGoodsInfoForPonHu(PhInventoryBaseDto inventoryDto) {
        Map<String,String> resultMap = new HashMap();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        try {
            log.info("获取胖总管接口地址：{}", createUrl);
            // 处理数据
            map = processingDataForCreate(inventoryDto);
            log.info("新增-推送胖总管接口数据Map类型：{}", map);
            log.info("新增-推送胖总管接口数据Json类型：{}", JsonUtils.toJson(inventoryDto));
            // 发送请求,返回请求结果
            resultMap = sendPostRequest(map, createUrl);
            log.info("新增-推送胖总管接口返回的信息：{},货品编码为：{}", resultMap,inventoryDto.getInventoryCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("新增-推送胖总管发布商品的货品编码为:{},出现异常：{}",inventoryDto.getInventoryCode(), e);
        } finally {

            return checkResult(resultMap,inventoryDto,map);
        }
    }

    // 校验推送胖总管商品的结果
    public Boolean checkResult(Map resultMap, PhInventoryBaseDto phInventoryBaseDto, MultiValueMap<String, Object> map){
        if (!("200").equals(String.valueOf(resultMap.getOrDefault("code","-1"))) &&
                !("132").equals(String.valueOf(resultMap.getOrDefault("code","-1")))) {
            // 校验是否已经存在错误的数据
            GoodsDataCreateorupdateLog goodsDataCreateorupdateLog = goodsDataCreateorupdateLogService
                    .getLog(phInventoryBaseDto.getInventoryCode(),"ponhu_add");
            if(ObjectUtils.isEmpty(goodsDataCreateorupdateLog)){
                // 需要根据来源进行判断是云商还是采购
                String str = "";
                if ((InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode())
                        .equals(phInventoryBaseDto.getInventoryChannel())) {
                    str = JsonUtils.toJson((PhInventoryForCloudTradeDto) phInventoryBaseDto);
                }else {
                    str = JsonUtils.toJson((PhInventoryForPurchaseDto) phInventoryBaseDto);
                }
                goodsDataCreateorupdateLogService.saveLog(
                        "ponhu_add",
                        "同步胖总管商品信息失败"+resultMap,
                        phInventoryBaseDto.getInventoryCode(),
                        str);
            }
            // 对接钉钉保障提醒
            String msg = dingTalkHandler.getMsgForPonHuByCreate(resultMap,map,createUrl);
            dingTalkHandler.sendMsg(msg, new ArrayList());
            log.error("推送胖总管商品信息失败,错误信息为{}", resultMap);
            return false;
        }
        return true;
    }

    /**
     * 更新商品信息
     *
     * @param phInventoryBaseDto
     * @return
     */
    public Boolean updateGoodsInfoForPonhu(PhInventoryBaseDto phInventoryBaseDto) {
        Map<String,String> resultMap = new HashMap();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        try {
            log.info("更新-推送胖总管接口地址为:{}",updateUrl);
            // 处理数据
            map = processingDataForUpdate(phInventoryBaseDto);
            log.info("更新-商品信息推送胖总管Map类型：{}", map);
            log.info("更新-商品信息推送胖总管Json类型：{}", JsonUtils.toJson(phInventoryBaseDto));
            // 发送请求,返回请求结果
            resultMap = sendPostRequest(map, updateUrl);
            log.info("更新-推送胖总管结果为:{},货品编码为：{}",resultMap,phInventoryBaseDto.getInventoryCode());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("更新-推送胖总管商品的货品编码为:{},出现异常：{},",phInventoryBaseDto.getInventoryCode(), e);
        } finally {
            if (!("200").equals(String.valueOf(resultMap.getOrDefault("code","-1")))) {
                log.error("胖总管更新商品失败,错误信息为{}", resultMap);
                if(!("100").equals(String.valueOf(resultMap.getOrDefault("code","-1")))){
                    // 校验是否已经存在错误的数据
                    GoodsDataCreateorupdateLog goodsDataCreateorupdateLog = goodsDataCreateorupdateLogService
                            .getLog(phInventoryBaseDto.getInventoryCode(),"ponhu_update");
                    if(ObjectUtils.isEmpty(goodsDataCreateorupdateLog)){
                        // 需要根据来源进行判断是云商还是采购
                        String str = "";
                        if ((InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode())
                                .equals(phInventoryBaseDto.getInventoryChannel())) {
                            str = JsonUtils.toJson((PhInventoryForCloudTradeDto) phInventoryBaseDto);
                        }else {
                            str = JsonUtils.toJson((PhInventoryForGoodsCenterDto) phInventoryBaseDto);
                        }
                        goodsDataCreateorupdateLogService.saveLog(
                                "ponhu_update",
                                "更新胖总管商品信息失败"+resultMap,
                                phInventoryBaseDto.getInventoryCode(),
                                str);
                    }
                }
                // 对接钉钉保障提醒
                String msg = dingTalkHandler.getMsgForPonHuByUpdate(resultMap,map,updateUrl);
                dingTalkHandler.sendMsg(msg, new ArrayList());
                if(("100").equals(String.valueOf(resultMap.getOrDefault("code","-1")))){
                    return true;
                }
                return false;
            }
        }
        return true;
    }

    public Map<String,String> sendPostRequest(MultiValueMap<String, Object> map, String url) {
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, new HttpHeaders());
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new WxMappingJackson2HttpMessageConverter());
        Map<String,String> restMap = restTemplate.postForObject(url, httpEntity, Map.class, map);
        return CollectionUtils.isEmpty(restMap) ? new HashMap() : restMap;
    }

    public MultiValueMap processingDataForUpdate(PhInventoryBaseDto phInventoryBaseDto) {
        MultiValueMap<String,Object> map = new LinkedMultiValueMap();
        if ((InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode())
                .equals(phInventoryBaseDto.getInventoryChannel())) {
            PhInventoryForCloudTradeDto phInventoryForCloudTradeDto =
                    (PhInventoryForCloudTradeDto) phInventoryBaseDto;
            map.add("w_price", phInventoryForCloudTradeDto.getWarehousingPrice());// 入库价
            map.add("gh_price", phInventoryForCloudTradeDto.getSupplyPrice());// 供货价
            map.add("b_price", phInventoryForCloudTradeDto.getSalesPriceGuidance());// 销售指导价
            map.add("goods_name", phInventoryForCloudTradeDto.getInventory().getInventoryName());// 商品名称
            map.add("goods_beizhu", phInventoryForCloudTradeDto.getInventory().getFlaw());// 商品备注
            map.add("countries", phInventoryForCloudTradeDto.getInventory().getProvenance());// 原产地
            map.add("fujian", phInventoryForCloudTradeDto.getAnnexs());// 附件
            map.add("attribute", phInventoryForCloudTradeDto.getPropertyMap());// 属性
            PhCategoryMapping phCategoryMapping = phCategoryMappingMapper.selectOne(
                    new LambdaQueryWrapper<PhCategoryMapping>().eq(
                            PhCategoryMapping::getGoodsCategoryId,
                            phInventoryForCloudTradeDto.getInventory().getCategoryId()));
            map.add("first_category_id", phCategoryMapping.getPonhuFirstCategoryId());// 一级分类
            map.add("second_category_id", phCategoryMapping.getPonhuSecondCategoryId());// 二级分类id
            map.add("goods_year", StringUtils.isBlank(phInventoryForCloudTradeDto.getInventory().getYear()) ?
                    "未知" : phInventoryForCloudTradeDto.getInventory().getYear());// 年份
        }else {
            PhInventoryForGoodsCenterDto phInventoryForGoodsCenterDto =
                    (PhInventoryForGoodsCenterDto) phInventoryBaseDto;
            map.add("w_price", phInventoryForGoodsCenterDto.getWarehousePrice());// 入库价
            map.add("gh_price", phInventoryForGoodsCenterDto.getSupplyTaxPrice());// 供货价
            map.add("b_price", phInventoryForGoodsCenterDto.getSaleTaxPrice());// 销售指导价
            map.add("appraiser", phInventoryForGoodsCenterDto.getAppraiserId());// 鉴定师
            map.add("goods_name", phInventoryForGoodsCenterDto.getInventoryName());// 商品名称
            map.add("goods_selling", phInventoryForGoodsCenterDto.getSellingPoint());// 商品卖点
            map.add("goods_beizhu", phInventoryForGoodsCenterDto.getFlaw());// 商品备注
            map.add("countries", phInventoryForGoodsCenterDto.getProvenance());// 原产地
            map.add("first_category_id", phInventoryForGoodsCenterDto.getFirstCategoryId());// 一级分类
            map.add("second_category_id", phInventoryForGoodsCenterDto.getSecondCategoryId());// 二级分类id
            map.add("fujian", phInventoryForGoodsCenterDto.getAnnexs());// 附件
            map.add("attribute", phInventoryForGoodsCenterDto.getPropertyMap());// 属性
            map.add("goods_year", StringUtils.isBlank(phInventoryForGoodsCenterDto.getYear()) ?
                    "未知" : phInventoryForGoodsCenterDto.getYear());// 年份
        }
        if(StringUtils.isNotBlank(phInventoryBaseDto.getMaterialId())){
            Material material = materialMapper.selectById(phInventoryBaseDto.getMaterialId());
            if (material.getOfficialPrice() != null) {
                map.add("original_price", material.getOfficialPrice());// 入库价
            }
            if (material.getSeriesId() != null) {
                PhSeries phSeries = phSeriesMapper.selectById(material.getSeriesId());
                map.add("goods_series", phSeries.getName());// 系列
            } else {
                map.add("goods_series", "未知系列");
            }
            if (material.getModelId() != null) {
                PhModel phModel = phModelMapper.selectById(material.getModelId());
                map.add("movement_model", phModel.getModel());// 型号
            } else {
                map.add("movement_model", "未知型号");
            }
        }
        map.add("uploadimages", phInventoryBaseDto.getImages());// 图片
        map.add("code", phInventoryBaseDto.getInventoryCode());// 货品编码
        map.add("cg_price", phInventoryBaseDto.getPurchasePrice());// 采购价
        map.add("chengse", phInventoryBaseDto.getQuality());// 成色id
        map.add("brand_id", phInventoryBaseDto.getBrandId());// 品牌id
        map.add("luxury",phInventoryBaseDto.getIsTwoLuxury());// 是否二奢
        map.add("selling_point_audio",phInventoryBaseDto.getSellingPointAudio());// 语音卖点
        return map;
    }

    public MultiValueMap<String, Object> processingDataForCreate(PhInventoryBaseDto inventoryDto) {
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        // 如果是云商
        if ((InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode())
                .equals(inventoryDto.getInventoryChannel())) {
            PhInventoryForCloudTradeDto phInventoryForCloudTradeDto = (PhInventoryForCloudTradeDto) inventoryDto;
            map.add("cg_price", phInventoryForCloudTradeDto.getPurchasePrice());// 四舍五入保留整数
            map.add("cost_price", phInventoryForCloudTradeDto.getCostPrice());// 胖总管的成本价=采购中心的采购价
            // 计算入库价,供货价,销售指导价
            map.add("w_price", phInventoryForCloudTradeDto.getWarehousingPrice());// 入库价
            map.add("gh_price", phInventoryForCloudTradeDto.getSupplyPrice());// 供货价
            map.add("b_price", phInventoryForCloudTradeDto.getSalesPriceGuidance());// 销售指导价
            map.add("shoppingid",phInventoryForCloudTradeDto.getShopId());
            map.add("countries", phInventoryForCloudTradeDto.getInventory().getProvenance());// 原产地
            map.add("goods_year", StringUtils.isBlank(phInventoryForCloudTradeDto.getInventory().getYear()) ?
                    "未知" : phInventoryForCloudTradeDto.getInventory().getYear());// 年份为空
        } else {
            PhInventoryForPurchaseDto phInventoryForPurchaseDto = (PhInventoryForPurchaseDto) inventoryDto;
            // 如果采购渠道为356,358的时候,根据采购中心传入的渠道,判断是否需要填充
            // 胖总管的采购价 = 采购中心的采购价*渠道系数+采购价
            /*if(goodsProperties.getErpChannelMap()
                    .containsKey(phInventoryForPurchaseDto.getErpChannelId())){
                map.add("cg_price", phInventoryForPurchaseDto.getPurchasePrice());// 采购价
                map.add("cost_price", phInventoryForPurchaseDto.getPurchasePrice());// 胖总管的成本价=采购中心的采购价
                map.add("gh_price",String.valueOf(phInventoryForPurchaseDto.getSalePrice()));// 供货
                map.add("b_price",String.valueOf(phInventoryForPurchaseDto.getSalePrice()));// 销售
                map.add("w_price", phInventoryForPurchaseDto.getPurchasePrice()
                        .multiply(new BigDecimal(phInventoryForPurchaseDto.getCoefficient()))
                        .add(phInventoryForPurchaseDto.getPurchasePrice())
                        .setScale(2, BigDecimal.ROUND_DOWN));// 入库价 保留两位小数
            }else {*/
                map.add("cg_price", phInventoryForPurchaseDto.getPurchasePrice()
                        .multiply(new BigDecimal(phInventoryForPurchaseDto.getCoefficient()))
                        .add(phInventoryForPurchaseDto.getPurchasePrice())
                        .setScale(2, BigDecimal.ROUND_DOWN));// 保留两位小数
                map.add("cost_price", phInventoryForPurchaseDto.getPurchasePrice());// 胖总管的成本价=采购中心的采购价
            //}
            // 判断是否标品二次采购
            if(phInventoryForPurchaseDto.getIsSecondPurchase()){
                Inventory inventoryByCode = inventoryService.getInventoryByCode(
                        phInventoryForPurchaseDto.getInventoryCode());
                GoodsInventoryMd goodsInventoryMd = goodsInventoryMdMapper.selectOne(
                        new LambdaQueryWrapper<GoodsInventoryMd>()
                                .eq(GoodsInventoryMd::getInventoryId, inventoryByCode.getId()));
                Goods goods = goodsMapper.selectById(goodsInventoryMd.getGoodsId());
                map.add("gh_price",goods.getSupplyTaxPrice());// 供货
                map.add("b_price",goods.getSaleTaxPrice());// 销售
                map.add("w_price", inventoryByCode.getWarehousePrice());// 入库价
            }
            // 展会寄售
            map.add("hzcontacts", phInventoryForPurchaseDto.getGoodsOwnerName());// 货主名称
            map.add("bdcontacts", phInventoryForPurchaseDto.getBdName());// bd联系人
            map.add("hpcontacts", phInventoryForPurchaseDto.getGoodsContactName());// 货品联系人
            map.add("goods_year", "未知");// 年份为空
        }
        // 市场价=物料中的官网售价,物料为空,则为空
        Material material = new Material();
        if (StringUtils.isNotBlank(inventoryDto.getMaterialId())) {
            // 查询物料
            material = materialMapper.selectById(inventoryDto.getMaterialId());
            if (ObjectUtils.isNotEmpty(material)) {
                if (material.getOfficialPrice() != null) {
                    map.add("original_price", material.getOfficialPrice());
                }
                // 根据物料信息,查询对应胖总管的品牌id和分类id
                PhBrand phBrand = phBrandMapper.selectById(material.getBrandId());
                map.add("brand_id", phBrand.getPonhuBrandId() == null ? "" : phBrand.getPonhuBrandId());
                PhCategoryMapping phCategoryMapping = phCategoryMappingMapper.selectOne(
                        new LambdaQueryWrapper<PhCategoryMapping>().eq(
                                PhCategoryMapping::getGoodsCategoryId, material.getCategoryId()));
                if (ObjectUtils.isNotEmpty(phCategoryMapping)) {
                    map.add("first_category_id", phCategoryMapping.getPonhuFirstCategoryId());
                    map.add("second_category_id", phCategoryMapping.getPonhuSecondCategoryId());
                }
                if (material.getSeriesId() != null) {
                    PhSeries phSeries = phSeriesMapper.selectById(material.getSeriesId());
                    map.add("goods_series", phSeries.getName());
                } else {
                    map.add("goods_series", "未知系列");
                }
                if (material.getModelId() != null) {
                    PhModel phModel = phModelMapper.selectById(material.getModelId());
                    map.add("movement_model", phModel.getModel());
                } else {
                    map.add("movement_model", "未知型号");
                }
                map.add("goods_name", StringUtils.isBlank(material.getMaterialName())
                        ? material.getMaterialCode() : material.getMaterialName());
                map.add("renqun", material.getApplyCrowd() == null ? "1" : material.getApplyCrowd());
            }
        } else {
            // 物料为空的时候,
            map.add("original_price", "未知");// 市场价
            PhBrand phBrand = phBrandMapper.selectById(inventoryDto.getBrandId());
            map.add("brand_id", phBrand.getPonhuBrandId());
            PhCategoryMapping phCategoryMapping = phCategoryMappingMapper.selectOne(new LambdaQueryWrapper<PhCategoryMapping>()
                    .eq(PhCategoryMapping::getGoodsCategoryId, inventoryDto.getCategoryId()));
            if (ObjectUtils.isNotEmpty(phCategoryMapping)) {
                map.add("first_category_id", phCategoryMapping.getPonhuFirstCategoryId());
                map.add("second_category_id", phCategoryMapping.getPonhuSecondCategoryId());
            }
            map.add("goods_series", "未知系列");// 系列默认为未知系列
            map.add("movement_model", "未知型号");// 型号默认为未知型号
            PhSysDictItem phSysDictItem = phSysDictItemService.getDictItemByValue(
                    DictConstant.CONDITION_TYPE,
                    inventoryDto.getQuality());
            map.add("goods_name", phSysDictItem.getLabel() + " " + phBrand.getEnName() + "/" + phBrand.getCnName());// 商品名称为成色+品牌名称
            //map.add("goods_year", "未知");// 年份为空
            map.add("renqun", "1");// 适用人群默认为1
        }

        map.add("chengse", inventoryDto.getQuality());// 成色
        map.add("uploadimages", inventoryDto.getImages());// 图片
        map.add("source",(InventoryChannelEnum.CLOUD_TRADE_JOINT_CONSIGNMENT.getCode())
                .equals(inventoryDto.getInventoryChannel())?"2":"1");// 货源
        map.add("code",inventoryDto.getInventoryCode());// 商品编码
        map.add("gotoware_type", inventoryDto.getWarehousingMethodId());// 入库方式
        map.add("con_name_id", inventoryDto.getGoodsOwnerId());// 货主id
        map.add("purchase_first_channel", inventoryDto.getFirstProcurementChannel()); // 一级采购渠道
        map.add("purchase_second_channel", inventoryDto.getSecondProcurementChannel());// 二级采购渠道
        // 是否二奢,商品数量
        map.add("luxury",inventoryDto.getIsTwoLuxury());
        map.add("goodsnum",inventoryDto.getGoodsNum());
        map.add("selling_point_audio",inventoryDto.getSellingPointAudio());// 语音卖点
        return map;
    }

}
